package sparkStream

import org.apache.kafka.clients.producer.{KafkaProducer, ProducerConfig, ProducerRecord}
import java.util.HashMap
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.SparkConf
import org.apache.spark.streaming.kafka010.KafkaUtils
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe

object SparkKafka {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf().setMaster("local[*]").setAppName("SparkKafkaStream")
    val ssc = new StreamingContext(conf, Seconds(2))
    ssc.sparkContext.setLogLevel("ERROR")

    val kfkaParams = Map[String, Object](
      "bootstrap.servers" -> "123.56.187.176:9092",
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> "cheng",
      "enable.auto.commit" -> (false: java.lang.Boolean),
      "auto.offset.reset" -> "earliest" // 从最早的偏移量开始读取
    )

    val topicName = Array("stuInfo")
    val streamRdd = KafkaUtils.createDirectStream[String, String](
      ssc,
      PreferConsistent,
      Subscribe[String, String](topicName, kfkaParams)
    )

    //  producer 配置项
    val property = new HashMap[String, Object]()
    property.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.234.110:9092")
    property.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer")
    property.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer")

    // 时间窗口 1
    // streamRddkafka 返回的数据 key，value 数据是value
    val res = streamRdd.map(_.value())
    val result = res.flatMap(_.split(" ")).map((_, 1)).reduceByKeyAndWindow(_ + _, Seconds(4), Seconds(4))
    result.foreachRDD(
      x => {
        println("--------数据是------")
        x.foreach(
          obj => {
            println(obj)
            //1 创建新的 客户端
            val producer = new KafkaProducer[String, String](property)
            // spark 链接 kafka,发送数据
            producer.send(new ProducerRecord[String, String]("15homework", obj.toString))
            producer.close()  // 关团
          }
        )
      }
    )

    ssc.start()
    ssc.awaitTermination()
  }
}